<template>
  <div class="tmpl">
    <h4>发表评论</h4>
    <hr>
    <textarea rows="3" placeholder="请输入评论内容（最多输入120字）" maxlength="120" v-model="msg"></textarea>
    <mt-button type="primary" size="large" @click="postcomment">发表评论</mt-button>

    <div class="comment-list">
      <div class="comment-box" v-for="(item, i) in list" :key="item.add_time">
        <div class="comment-title">
          第{{i+1}}楼&nbsp;用户：{{item.user_name}}&nbsp;发表时间&nbsp;{{item.add_time | dataFormat}}
        </div>
        <div class="comment-content">
          {{item.content}}
        </div>
      </div>
    </div>

    <mt-button type="danger" size="large" plain @click="loadMore">加载更多</mt-button>
  </div>
</template>

<script>
import { Toast } from 'mint-ui'

export default {
  data() {
    return {
      pageIndex: 1,
      list: [],
      msg: ''
    }
  },
  created() {
    this.getCommentList();
  },
  methods: {
    getCommentList() {
      var url = 'api/getcomments/' + this.artId + '?pageindex=' + this.pageIndex;
      this.$http.get(url).then(res => {
        var result = res.body;
        if (result.status === 0) {
          console.log(result.message);
          // this.list = result.message;
          this.list = this.list.concat(result.message);
        } else {
          console.log('获取评论列表失败！');
        }
      });
    },
    loadMore() {
      this.pageIndex++;
      this.getCommentList();
    },
    postcomment() {
      if (this.msg.trim().length <= 0) {
        return;
      }

      var url = 'api/postcomment/' + this.artId;
      this.$http.post(url, { content: this.msg }, { emulateJSON: true }).then(res => {
        var result = res.body;
        if (result.status === 0) {
          this.list.unshift({ user_name: '匿名用户', add_time: Date.now(), content: this.msg });
          Toast('添加评论成功！');
        } else {
          console.log('添加评论失败！');
        }
      });
    }
  },
  props: ['artId']
}
</script>

<style lang="scss" scoped>
.tmpl {
  textarea {
    font-size: 14px;
    margin: 5px 0px;
  }

  .comment-list {
    margin: 10px 0;
    .comment-box {
      .comment-title {
        font-size: 13px;
        background-color: #ccc;
        line-height: 35px;
      }
      .comment-content {
        height: 40px;
        line-height: 40px;
        font-size: 14px;
        text-indent: 2em;
      }
    }
  }
}
</style>
